package cn.bsuc.crm.aop;

import cn.bsuc.crm.annotation.WebLog;
import cn.bsuc.crm.entity.Log;
import cn.bsuc.crm.entity.User;
import cn.bsuc.crm.service.LogService;
import cn.bsuc.crm.util.Code;
import cn.bsuc.crm.util.JwtUtils;
import cn.bsuc.crm.util.Result;
import cn.bsuc.crm.util.UserHolder;
import com.alibaba.fastjson2.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author : zhuoyuan
 * @date : 2022/10/9 17:28
 * @description : 日志切面类
 */
@Aspect
@Component
public class WebLogAop {

    @Autowired
    private LogService logService;

    /*
       定义切点，指定在哪里执行（切点表达式里定义）
     */
    @Pointcut("execution(* cn.bsuc.crm.controller.*.*(..))")
    public void logPointcut(){}

    /**
     * 1 指定要干啥（方法体内容），
     * 2 执行的时机（指定通知类型）
     */
    @AfterReturning(pointcut = "logPointcut()", returning = "obj")
    public void saveLog(JoinPoint joinPoint,Object obj){
        //RequestContextHolder是 spring 提供的类，用来获得请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //获得HttpServletRequest
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //从切面joinPoint对象中获得织入的方法（调用的方法）
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        //获得方法
        Method method = signature.getMethod() ;
        //获得方法上的注解
        if (method.isAnnotationPresent(WebLog.class)) {
            WebLog webLog = method.getAnnotation(WebLog.class);
            //获取注解上的属性值
            String module = webLog.module();
            String opt = webLog.opt();

            Log log = new Log();
            //模块
            log.setDescription(module);
            //类型
            log.setType(opt);
            //方法名
            log.setMethod(method.getName());
            // TODO 请求 IP
            //返回状态码
            Result result = (Result) obj;
            log.setExceptionCode(result.getCode()+"");
            if (result.getCode() == Code.OK) {
                log.setExceptionDetail("操作成功");
            }else {
                log.setExceptionDetail("操作失败");
            }

//            String token = request.getHeader("token");
//            if (token != null){
//                // 创建者
//                User user = UserHolder.getUser();
//                System.out.println();
//                System.out.println("+++++++++++++++>>>>  "+user);
//                log.setCreateMan(user.getUserName());
//                System.out.println();
//            }

            // 创建者
            User user = UserHolder.getUser();
            log.setCreateMan(user.getUserName());

            log.setResult(JSON.toJSONString(result));
            logService.save(log);

        }


    }


}
